package com.xiaoai.io.bio5file;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * @Author
 * @Date 2021-09-06 22:34
 */
public class ServerReaderThread extends Thread{

    private Socket socket;
    public ServerReaderThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            // 得到数据输入流读取客户端发送的数据
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            // 读取客户端发送的文件类型
            String suffix = dis.readUTF();
            System.out.println("服务端接收到文件类型："+suffix);
            // 定义一个字节输入管道
            String fileName = UUID.randomUUID().toString() + suffix;
            OutputStream os = new FileOutputStream("res\\server\\" + fileName);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = dis.read(buffer))> 0){
                os.write(buffer, 0, len);
            }
            os.close();
            System.out.println(String.format("服务端接收文件保存成功！[%s]",fileName));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
